﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace PlayDeezGames.Common
{
    public abstract class EntityBase:IEntity
    {
        private IEntity parentEntity = null;
        public IEntity ParentEntity
        {
            get
            {
                return parentEntity;
            }
            set
            {
                if (ParentEntity != null)
                {
                    ParentEntity.RemoveChild(this);
                }
                parentEntity = value;
                if (ParentEntity != null)
                {
                    ParentEntity.AddChild(this);
                }
            }
        }

        private List<IEntity> children = new List<IEntity>();

        public IEnumerable<IEntity> Children
        {
            get { return children; }
        }

        protected EntityBase():this(null)
        {
        }

        protected EntityBase(IEntity theParentEntity)
        {
            ParentEntity = theParentEntity;
        }

        protected EntityBase(IEntity theParentEntity, XElement theXElement):this(theParentEntity)
        {
            FromXElement(theXElement);
        }

        protected abstract XElement OnToXElement();
        public XElement ToXElement()
        {
            XElement result = OnToXElement();
            foreach (IEntity child in Children)
            {
                result.Add(child.ToXElement());
            }
            return result;
        }
        protected abstract void OnFromXElement(XElement theXElement);
        public void FromXElement(XElement theXElement)
        {
            foreach (XElement element in theXElement.Elements())
            {
                EntityFactories.Load(this, element);
            }
            OnFromXElement(theXElement);
        }


        public bool AddChild(IEntity theChild)
        {
            if (children.Contains(theChild)) return false;
            children.Add(theChild);
            return true;
        }

        public bool RemoveChild(IEntity theChild)
        {
            if (!children.Contains(theChild)) return false;
            children.Remove(theChild);
            return true;
        }
    }
}
